from django import http
from django.shortcuts import render
from django.views import View
from django.core.paginator import Paginator
from haystack.views import SearchView

from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from apps.goods.utils import get_breadcrumb, get_goods_specs
from meiduo_mall.settings.dev import logger


class DetailVisitView(View):
    def post(self, request, category_id):

        # 1.接收参数 category_id
        # 2.校验参数
        try:
            cat3 = GoodsCategory.objects.get(pk=category_id)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '参数有误!'})

        # 3.判断 当天 有没有 这个分类的 记录数据
        from datetime import date
        today_date = date.today()

        try:
            # 1.GoodsVisitCount
            # goods_visit = GoodsVisitCount.objects.get(date=today_date, category=cat3)

            # 2,GoodsCategory
            goods_visit = cat3.goodsvisitcount_set.get(date=today_date)
        except Exception as e:
            # 如果没有  新建一条
            goods_visit = GoodsVisitCount()

        # 4.累加个数  += 1
        goods_visit.count += 1
        goods_visit.category = cat3
        goods_visit.save()

        # 5.返回Json
        return http.JsonResponse({'code': 0, 'errmsg': '记录成功!'})


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        goods_specs = get_goods_specs(sku)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


class MySearchView(SearchView):
    # 重写父类  create_response
    def create_response(self):
        # 1.接收参数
        query = self.request.GET.get('q')

        # 2.获取  haystack 返回的数据
        context = self.get_context()

        # 3.转换 前端的数据格式
        data_list = []
        skus = context['page'].object_list
        for sku in skus:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': query,
                # 'page_size': context['paginator'].num_pages,
                # 'count': context['paginator'].count,
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })

        # 4.返回 Json safe=False----默认 只能转换dict --list ---safe=False
        return http.JsonResponse(data_list, safe=False)


class HotGoodsView(View):
    def get(self, request, category_id):
        # 4.校验category_id
        try:
            GoodsCategory.objects.get(pk=category_id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '分类不存在!'})

        # 5.根据category_id 查询对应的sku ---排序 销量降序-sales -- 切片[:2]
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        # 6.python对象---[{}]
        hot_list = []
        for sku in skus:
            hot_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        # 7.返回响应
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': hot_list})


class ListView(View):
    def get(self, request, category_id):
        # 1.接收参数
        # 当前页面  page
        page = request.GET.get('page')
        # 页面显示页数  page_size
        page_size = request.GET.get('page_size')
        # 排序参数  ordering
        sort = request.GET.get('ordering')

        # 2.校验参数--category_id  是否真的有
        try:
            cat3 = GoodsCategory.objects.get(pk=category_id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '参数有误! '})

        # 3.根据 cat3 去SKU表 查询对应的数据
        # SKU.objects.filter(category_id=category_id)
        skus = SKU.objects.filter(category=cat3, is_launched=True).order_by(sort)

        # 4.获取面包屑组件数据 cat3--cat2-cat1
        breadcrumb = get_breadcrumb(cat3)

        # 5.将skus 进行分页处理
        paginator = Paginator(skus, page_size)
        # 获取总页数
        total_page = paginator.num_pages
        # 获取当前页的 数据对象  skus
        page = paginator.page(page)

        # 6.将python对象的查询集 数据---转换成 { [ {}]} json格式
        data_list = []
        for sku in page:
            data_list.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price  # Decimal('6499.00')
            })

        # 7.返回前端
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'breadcrumb': breadcrumb,
            'list': data_list,
            'count': total_page
        })
